package com.rfs.utils;

import org.apache.commons.lang3.StringUtils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * @author renfushuai
 * @date 2022/6/16
 */
public class TimeUtil {
    public static final ZoneId CTT_ZONE_ID = ZoneId.of(ZoneId.SHORT_IDS.get("CTT"));
    public static final DateTimeFormatter CTT_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
      /*  LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(1655343719398L), CTT_ZONE_ID);
        String format = localDateTime.format(CTT_DATE_TIME_FORMATTER);
        System.out.println(format);*/
        System.out.printf(secondsToLocalDateTime(1675041888L).toString());
    }

    public static LocalDateTime secondsToLocalDateTime(Long seconds) {
        if (seconds == null) {
            return null;
        }
        // millis
        return millisToLocalDateTime(seconds * 1000L);
    }

    public static LocalDateTime millisToLocalDateTime(Long millis) {
        if (millis == null) {
            return null;
        }
        // millis
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), CTT_ZONE_ID);
    }


    public static Instant toInstant(String timeStr, DateTimeFormatter dateTimeFormatter) {
        return LocalDateTime
                .parse(timeStr, dateTimeFormatter)
                .atZone(CTT_ZONE_ID)
                .toInstant();
    }

    public static final LocalDateTime EMPTY_TIME = LocalDateTime.ofInstant(
            toInstant("2000-01-01 00:00:00",
                    CTT_DATE_TIME_FORMATTER), CTT_ZONE_ID);

    public static LocalDateTime toLocalDateTime(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        if (str.length() == 10) {
            str += " 00:00:00";
        }
        return filter(LocalDateTime.parse(str.contains("T") ? str.replace("T", " ") : str, CTT_DATE_TIME_FORMATTER));
    }

    public static LocalDateTime filter(LocalDateTime target) {
        if (target == null) {
            return null;
        }
        LocalDateTime emptyTime = EMPTY_TIME;
        if (target.equals(emptyTime) || target.isBefore(emptyTime)) {
            return null;
        }
        return target;
    }

}
